#!/usr/bin/python

import subprocess
from pathlib import Path
import json
import pickle
import time
import threading

OUT = f"{Path.home()}/.config/hypr/store/dynamic_out.txt"
# PREV_PATH = f"{Path.home()}/.config/hypr/store/prev.txt"
prev = None

def print(ar):
    with open(OUT,"w") as f:
        f.write(json.dumps(ar))

# with open(f"{Path.home()}/.config/hypr/im_here","w") as f:
#     f.write("")

global PAUSE_MEDIA
PAUSE_MEDIA = False

def notif_watcher():
    with open(f"{Path.home()}/.config/hypr/store/latest_notif","rb") as f:
        global prev
        try:
            new = pickle.load(f)
        except:
            new = prev
        if new != prev:
                print(json.dumps({"class":"none","text":""}))
                global PAUSE_MEDIA
                PAUSE_MEDIA = True
                urgency = "low"
                if new["urgency"] == "CRITICAL":
                    urgency = "critical"
                elif new["urgency"] == "NORMAL":
                    urgency = "normal"
                doc = {
                        "class":urgency,
                        "text":f'[{new["app_name"]}]   {new["summary"]}',
                        "tooltip":"notification"
                }
                print(doc)
                time.sleep(3)
                print({"class":"none","text":""})
                PAUSE_MEDIA = False
                prev = new


def start_watcher():
    while 1:
        notif_watcher()
        time.sleep(0.5)


def debug():
    while 1:
        print(PAUSE_MEDIA)
        time.sleep(0.5)
t = threading.Thread(target=start_watcher)
d = threading.Thread(target=debug)
t.start()
#d.start()



with open("test.log", "wb") as f:
    process = subprocess.Popen(
        "waybar-mpris --position --autofocus".split(),
         stdout=subprocess.PIPE
    )
    print(json.dumps({"class":"none","text":""}))
    for line in iter(lambda: process.stdout.readline().decode("utf-8"), b""):
        dat = json.loads(line)
        if not PAUSE_MEDIA:
            if "text" in dat:
                dat["text"] = dat["text"].replace(" ", "").replace("", "")
                print(dat)
            else:
                print({"class":"none","text":""})

t.join()
#d.join()
        
